package cn.interceptor;

import cn.common.ResultCode;
import cn.exception.CommonException;
import cn.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * SpringMVC提供的
 * ：自定义拦截器
 * 简化获取token数据的代码编写
 * ：统一的用户权限校验
 * ：判断用户是否具有当前访问接口的权限
 *
 * @author Mxb
 * @version 1.0
 * @date 2020/7/5 13:29
 */
@Component //创建对象 交给spring管理
public class JwtInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JWTUtils jwtUtils;

    /**
     * 进入控制器方法之前执行的内容
     * 必须有返回值
     * boolean:
     * true : 可以继续执行控制器方法
     * false: 拦截请求
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 简化获取token数据的代码编写（判断是否登录）
         * 通过request 获取请求token信息
         * 从token中解析后去claims
         * 将claims 绑定到request域中
         */
        //通过request 获取请求token信息
        String authorization = request.getHeader("Authorization");
        if (authorization == null) {
            throw new CommonException(ResultCode.UNAUTHENTICATED);
        }
        // 解析token
        Claims claims = jwtUtils.parseJWT(authorization);
        if (claims == null) {
            throw new CommonException(ResultCode.UNAUTHENTICATED);
        }
        request.setAttribute("user_claims", claims);
        // 让程序继续往下执行
        return true;
    }

    /**
     * 执行控制器方法之后执行的内容
     * ：使用较少
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 响应结束之前 执行的内容
     * ：使用较少
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
